package com.davidlife.security.digitaldigest;

import com.davidlife.security.binarycodingstr.HexCoding;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA1Digest {
    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String message = "hello, i am davidlife, good night!";
        System.out.println("使用JDK自带的SHA-1: " + SHA1ByJdk(message));

        System.out.println("使用Apache 的SHA-1: " + SHA1ByApache(message));
    }
    //JDK 自带的SHA-1使用方法
    public static String SHA1ByJdk(String message) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] bytes = md.digest(message.getBytes("utf8"));
        return HexCoding.bytes2HexString(bytes);
    }

    //Apache的commons-codec中的DigestUtils
    public static String SHA1ByApache(String text) {
        //加密后的字符串
        String encodeStr = org.apache.commons.codec.digest.DigestUtils.sha1Hex(text);
        return encodeStr;
    }

}
